package com.example.a260219.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private String TAG="wifitest";
    private WifiManager wifiManager;
    private   int wifiState;

    private TextView tv;
    private TextView tv1;
    private List<ScanResult> scanResults;
    private Handler handle=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            scanResults= (List<ScanResult>) msg.obj;
            showScanResults();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv= (TextView) findViewById(R.id.tv);
        tv1= (TextView) findViewById(R.id.tv1);
        //获取wifiManager实例对象
         wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        //开启, 关闭 WiFi:
        wifiManager.setWifiEnabled(true);
        wifiManager.startScan();
        //获取扫描到的 WiFi 热点的结果:
        wifiState = wifiManager.getWifiState();
        wifiState();
        //在确认开启 WiFi 之后, 我们就可以调用 startScan() 函数开始扫描附近的热点了, 即:
        Intent intent=new Intent();
        boolean isScanned = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, true);
        Log.i(TAG, "isScanned = " + isScanned);
        if(isScanned){
            //运行时权限
            if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                //用户未授权 去授权
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},1);
            }else {
                getScanResults();
            }
        }

        //然后, 我们看一下扫描到的结果是一个怎么样的构成?
        showScanResults();
        /*获取配置好的 WiFi 信息:之前连接过的wifi
        参考地址：https://blog.csdn.net/lemon_tree12138/article/details/38871341
        下面我来简单介绍一下关于WIFI的WifiConfiguration类。api中是这样介绍这个类的：

        A class representing a configured Wi-Fi network, including the security configuration. Android will not necessarily support all of these security schemes initially.

        ——这是一个代表已配置的Wi-Fi网络的类，也包括安全配置。 Android将不一定支持所有的这些最初的保障计划。

        所以，这个类就是包含了一些已经配置好的WI-FI网络，如当前正在连接的WI-FI网络信息。

        获取方式：
        WifiInfo info = wifiManager.getConnectionInfo();
        getBSSID() 获取BSSID属性
        getDetailedStateOf() 获取客户端的连通性
        getHiddenSSID() 获取SSID 是否被隐藏
        getIpAddress() 获取IP 地址
        getLinkSpeed() 获取连接的速度
        getMacAddress() 获取Mac 地址
        getRssi() 获取802.11n 网络的信号
        getSSID() 获取SSID
        getSupplicanState() 获取具体客户端状态的信息
         */
        List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks();
        //然后, 我们看一下扫描到的结果是一个怎么样的构成?
        if (wifiConfigurations == null || wifiConfigurations.isEmpty()) return;
        Log.i(TAG, "configuration size = " + wifiConfigurations.size());
        for (WifiConfiguration configuration : wifiConfigurations) {
            Log.i(TAG, "configuration = " + configuration.toString());
        }
        //获取当前wifi连接信息
        WifiInfo info = wifiManager.getConnectionInfo();
        int ipAddress=info.getIpAddress();
        String ip = intToIp(ipAddress);
        String mac=info.getMacAddress();
        Log.i(TAG, "configuration = " + info.toString());
        Log.i(TAG, "ip = " + ip);
        Log.i(TAG, "mac = " + mac);
        tv1.setText(ip);

    }

    private void wifiState() {
        switch (wifiState){
            case  WifiManager.WIFI_STATE_ENABLING://2
                myToast("WiFi正要开启的状态");
                break;
            case  WifiManager.WIFI_STATE_ENABLED://3
                myToast("WiFi已经完全开启的状态");
                break;
            case  WifiManager.WIFI_STATE_DISABLING://0
                myToast("WiFi正要关闭的状态");
                break;
            case  WifiManager.WIFI_STATE_DISABLED://1
                myToast("WiFi已经完全关闭的状态");
                break;
            case  WifiManager.WIFI_STATE_UNKNOWN://4
                myToast("WiFi未知的状态");
                break;
            default: myToast("WiFi未知的状态");
                break;
        }
    }

    private void myToast(String str) {
        Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
    }
    private List<ScanResult>  getScanResults(){
        scanResults = wifiManager.getScanResults();
        Log.i(TAG, "scanResults size = " + scanResults.size());
        return scanResults;
    }
   private void showScanResults(){
       String strs="";
       if (scanResults == null || scanResults.isEmpty()) return;
       for (ScanResult result : scanResults) {
           strs+="\n设备名："+result.SSID
                   +"\n信号强度："+wifiManager.calculateSignalLevel(result.level,1001)+"\n";
           Log.i(TAG, "result = " + strs);
       }
       tv.setText("结果:"+strs);
   }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case  1:
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    getScanResults();
                    //通过一个handler 刷新界面显示
                    Message msg=new Message();
                    msg.obj=scanResults;
                    handle.sendMessage(msg);
                }
                break;
            default:
                break;
        }
    }
    //ip进行位运算
    private String intToIp(int i) {

        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }
}
